The execa npm package is a process execution tool that simplifies working with child processes in Node.js. It provides a better user experience than the default child_process module by offering a promise-based API, improved Windows support, and additional convenience options.
What are execa's main functionalities?
Executing a shell command
This feature allows you to execute a shell command and obtain the result. The example shows how to execute the 'echo' command and print 'unicorns' to the console.
This feature is used to execute a command synchronously, blocking the event loop until the process has finished. The example synchronously executes the 'echo' command and logs the result.
This feature allows you to stream the output of a command directly to the console or another stream. The example streams the output of the 'echo' command to the process's stdout.
ShellJS is a portable Unix shell commands implementation for Node.js. It offers a higher-level API for executing commands but does not support returning promises natively.
Cross-spawn is a cross-platform solution for spawning child processes. It aims to solve compatibility issues on Windows but does not provide a promise-based API.
import {execa} from'execa';
// Similar to `echo unicorns > stdout.txt` in Bashawaitexeca('echo', ['unicorns']).pipeStdout('stdout.txt');
// Similar to `echo unicorns 2> stdout.txt` in Bashawaitexeca('echo', ['unicorns']).pipeStderr('stderr.txt');
// Similar to `echo unicorns &> stdout.txt` in Bashawaitexeca('echo', ['unicorns'], {all: true}).pipeAll('all.txt');
Redirect input from a file
import {execa} from'execa';
// Similar to `cat < stdin.txt` in Bashconst {stdout} = awaitexeca('cat', {inputFile: 'stdin.txt'});
console.log(stdout);
//=> 'unicorns'
Save and pipe output from a child process
import {execa} from'execa';
const {stdout} = awaitexeca('echo', ['unicorns']).pipeStdout(process.stdout);
// Prints `unicorns`console.log(stdout);
// Also returns 'unicorns'
Pipe multiple processes
import {execa} from'execa';
// Similar to `echo unicorns | cat` in Bashconst {stdout} = awaitexeca('echo', ['unicorns']).pipeStdout(execa('cat'));
console.log(stdout);
//=> 'unicorns'
Executes a command. The command string includes both the file and its arguments. Returns a childProcess.
Arguments are automatically escaped. They can contain any character, but spaces must use ${} like $`echo ${'has space'}`.
This is the preferred method when executing multiple commands in a script file.
The command string can inject any ${value} with the following types: string, number, childProcess or an array of those types. For example: $`echo one ${'two'} ${3} ${['four', 'five']}`. For ${childProcess}, the process's stdout is used.
Executes a command. The command string includes both the file and its arguments. Returns a childProcess.
Arguments are automatically escaped. They can contain any character, but spaces must be escaped with a backslash like execaCommand('echo has\\ space').
This is the preferred method when executing a user-supplied command string, such as in a REPL.
For all the methods above, no shell interpreter (Bash, cmd.exe, etc.) is used unless the shell option is set. This means shell-specific characters and expressions ($variable, &&, ||, ;, |, etc.) have no special meaning and do not need to be escaped.
Same as the original child_process#kill() except: if signal is SIGTERM (the default value) and the child process is not terminated after 5 seconds, force it by sending SIGKILL.
Note that this graceful termination does not work on Windows, because Windows doesn't support signals (SIGKILL and SIGTERM has the same effect of force-killing the process immediately.) If you want to achieve graceful termination on Windows, you have to use other means, such as taskkill.
options.forceKillAfterTimeout
Type: number | false
Default: 5000
Milliseconds to wait for the child process to terminate before sending SIGKILL.
If the target is another execa() return value, it is returned. Otherwise, the original execa() return value is returned. This allows chaining pipeStdout() then awaiting the final result.
The stdout option must be kept as pipe, its default value.
pipeStderr(target)
Like pipeStdout() but piping the child process's stderr instead.
The stderr option must be kept as pipe, its default value.
This is meant to be copy and pasted into a shell, for debugging purposes.
Since the escaping is fairly basic, this should not be executed directly as a process, including using execa() or execaCommand().
exitCode
Type: number
The numeric exit code of the process that was run.
stdout
Type: string | Buffer
The output of the process on stdout.
stderr
Type: string | Buffer
The output of the process on stderr.
all
Type: string | Buffer | undefined
The output of the process with stdout and stderr interleaved.
You can cancel the spawned process using the signal option.
killed
Type: boolean
Whether the process was killed.
signal
Type: string | undefined
The name of the signal that was used to terminate the process. For example, SIGFPE.
If a signal terminated the process, this property is defined and included in the error message. Otherwise it is undefined.
signalDescription
Type: string | undefined
A human-friendly description of the signal that was used to terminate the process. For example, Floating point arithmetic error.
If a signal terminated the process, this property is defined and included in the error message. Otherwise it is undefined. It is also undefined when the signal is very uncommon which should seldomly happen.
cwd
Type: string
The cwd of the command if provided in the command options. Otherwise it is process.cwd().
message
Type: string
Error message when the child process failed to run. In addition to the underlying error message, it also contains some information related to why the child process errored.
The child process stderr then stdout are appended to the end, separated with newlines and not interleaved.
shortMessage
Type: string
This is the same as the message property except it does not include the child process stdout/stderr.
originalMessage
Type: string | undefined
Original error message. This is the same as the message property except it includes neither the child process stdout/stderr nor some additional information added by Execa.
This is undefined unless the child process exited due to an error event or a timeout.
options
Type: object
cleanup
Type: boolean
Default: true
Kill the spawned process when the parent process exits unless either:
- the spawned process is detached
- the parent process is terminated abruptly, for example, with SIGKILL as opposed to SIGTERM or a normal exit
preferLocal
Type: boolean
Default: true with $, false otherwise
Prefer locally installed binaries when looking for a binary to execute.
If you $ npm install foo, you can then execa('foo').
localDir
Type: string | URL
Default: process.cwd()
Preferred path to find locally installed binaries in (use with preferLocal).
For example, this can be used together with get-node to run a specific Node.js version in a child process.
buffer
Type: boolean
Default: true
Buffer the output from the spawned process. When set to false, you must read the output of stdout and stderr (or all if the all option is true). Otherwise the returned promise will not be resolved/rejected.
Specify the kind of serialization used for sending messages between processes when using the stdio: 'ipc' option or execaNode():
- json: Uses JSON.stringify() and JSON.parse().
- advanced: Uses v8.serialize()
Prepare child to run independently of its parent process. Specific behavior depends on the platform.
uid
Type: number
Sets the user identity of the process.
gid
Type: number
Sets the group identity of the process.
shell
Type: boolean | string
Default: false
If true, runs file inside of a shell. Uses /bin/sh on UNIX and cmd.exe on Windows. A different shell can be specified as a string. The shell should understand the -c switch on UNIX or /d /s /c on Windows.
We recommend against using this option since it is:
not cross-platform, encouraging shell-specific syntax.
slower, because of the additional shell interpretation.
unsafe, potentially allowing command injection.
encoding
Type: string | null
Default: utf8
Specify the character encoding used to decode the stdout and stderr output. If set to null, then stdout and stderr will be a Buffer instead of a string.
timeout
Type: number
Default: 0
If timeout is greater than 0, the parent will send the signal identified by the killSignal property (the default is SIGTERM) if the child runs longer than timeout milliseconds.
maxBuffer
Type: number
Default: 100_000_000 (100 MB)
Largest amount of data in bytes allowed on stdout or stderr.
killSignal
Type: string | number
Default: SIGTERM
Signal value to be used when the spawned process will be killed.
When AbortController.abort() is called, .isCanceled becomes false.
Requires Node.js 16 or later.
windowsVerbatimArguments
Type: boolean
Default: false
If true, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to true automatically when the shell option is true.
windowsHide
Type: boolean
Default: true
On Windows, do not create a new console window. Please note this also prevents CTRL-Cfrom working on Windows.
execa can be combined with get-bin-path to test the current package's binary. As opposed to hard-coding the path to the binary, this validates that the package.jsonbin field is correctly set up.
We found that execa demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.It has 2 open source maintainers collaborating on the project.
Package last updated on 27 Jul 2023
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.